package com.lcq.demo.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.lcq.demo.common.entity.Result;
import com.lcq.demo.entity.dto.ThingShadowDTO;
import com.lcq.demo.service.IoTService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Tag(name = "IOT模块")
@RestController
@RequestMapping("/api/device")
@Slf4j
//@CrossOrigin(origins = "*", allowedHeaders = "token")
public class IOTController {

    @Resource
    private IoTService iotService;

    /**
     * 获取设备影子信息
     */
    @Operation(summary = "获取设备影子信息")
    @GetMapping("/shadow/{thingName}")
    public Result<ThingShadowDTO> getDeviceShadow(@PathVariable String thingName) {
        try {
            if (log.isInfoEnabled()) {
                log.info("IOTController.getDeviceShadow.thingName:{}", thingName);
            }
            Preconditions.checkArgument(!StringUtils.isEmpty(thingName), "设备名不能为空！");
            return Result.ok(iotService.getDeviceShadow(thingName));
        } catch (Exception e) {
            log.error("IOTController.getDeviceShadow.thingShadowDTO.error:{}", e.getMessage(), e);
            return Result.fail("获取设备影子失败！");
        }
    }

    /**
     * 更新设备影子信息
     */
    @Operation(summary = "更新设备影子信息")
    @PutMapping("/shadow")
    public Result<String> updateDeviceShadow(@RequestBody ThingShadowDTO thingShadowDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("IOTController.updateDeviceShadow.thingShadowDTO.thingName:{}, shadowDoc:{}", thingShadowDTO.getThingName(), thingShadowDTO.getShadowJson().toString());
            }
            Preconditions.checkArgument(!StringUtils.isEmpty(thingShadowDTO.getThingName()), "设备名不能为空！");
            Preconditions.checkNotNull(thingShadowDTO.getShadowJson(), "shadowDoc不能为空！");
            iotService.updateThingShadow(thingShadowDTO);
            return Result.ok("更新影子设备成功");
        } catch (Exception e) {
            log.error("IOTController.updateDeviceShadow.error:{}", e.getMessage(), e);
            return Result.fail("更新设备影子失败！");
        }
    }


}
